<template>
  <div>
    <el-card>
      <Catgory :scene="scene"></Catgory>
    </el-card>
    <el-card shadow="hover" style="margin-top: 10px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          :disabled="categoryStore.c3Id ? false : true"
          @click="changeScene"
          >添加平台属性</el-button
        >
        <el-table border style="margin-top: 10px" :data="attrList">
          <el-table-column
            label="序号"
            width="80"
            align="center"
            prop="id"
          ></el-table-column>
          <el-table-column
            label="属性名"
            prop="attrName"
            width="100"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag
                v-for="attrValue in row.attrValueList"
                :key="attrValue"
                style="margin: 0px 5px"
                class="ml-2"
              >
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="考虑"
                :icon="InfoFilled"
                icon-color="#626AEF"
                width="200"
                :title="`你确定要删除${row.attrName}?`"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名字">
            <el-input
              placeholder="请你输入属性的名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          :icon="Plus"
          :disabled="!attrParams.attrName"
          @click="addAttr"
          >添加属性值</el-button
        >
        <el-table
          border
          stripe
          style="margin: 10px 0px"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            type="index"
            align="center"
            width="80"
            label="序号"
          ></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-input
                placeholder="请你输入属性值"
                v-model="row.valueName"
                @blur="toLook(row, $index)"
                v-if="row.flag"
                :ref="(el) => (inputArr[$index] = el)"
              ></el-input>
              <span
                v-else
                @click="toEdit(row, $index)"
                style="display: block"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="考虑"
                :icon="InfoFilled"
                icon-color="#626AEF"
                width="200"
                :title="`你确定要删除属性值${row.valueName}`"
                @confirm="removeAttrValue($index)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="default" @click="save">保存</el-button>
        <el-button size="default" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, nextTick, onUnmounted } from "@vue/runtime-core";
import { useCategoryStore } from "@/stores/catgory";
import {
  reqAddOrUpdateAttr,
  reqGetAttrList,
  reqRemoveAttr,
} from "@/api/product/attr";
import { Delete, Edit, InfoFilled, Plus } from "@element-plus/icons-vue";
import type { attrResponseDataType } from "@/api/product/attr/model";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash-es";

//获取仓库
let categoryStore = useCategoryStore();

//存储平台属性的数据的数据
let attrList = ref<attrResponseDataType>([]);
//定义新增平台属性接口需要携带参数
let attrParams: any = reactive({
  attrName: "", //新增平台属性的属性名字
  attrValueList: [], //收集新增的属性值的数据   //占位:先假装收集一个属性值
  categoryId: 0, //某一个三级分类的ID
  categoryLevel: 3, //代表的是给三级分类新增平台属性
});

//定义响应式数据切换场景
let scene = ref(0);

//定义响应式数据input组件实例的数组
let inputArr: any = ref([]);

//获取平台属性函数的封装
const getAttrList = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  let result: attrResponseDataType = await reqGetAttrList(c1Id, c2Id, c3Id);
  attrList.value = result;
};
//监听事件源 监听事件回调
watch(
  () => categoryStore.c3Id.value,
  async () => {
    //每一次监听到c3Id变化:上一次存储数据不在保留
    attrList.value = [];
    //监听c3Id变化:但是保证c3Id不能是空字符串
    if (categoryStore.c3Id === "") return;
    getAttrList();
  },
  { deep: true }
);

//修改场景切换
const changeScene = () => {
  //先把上一次的数据清空
  Object.assign(attrParams, {
    attrName: "", //新增平台属性的属性名字
    attrValueList: [], //收集新增的属性值的数据   //占位:先假装收集一个属性值
    categoryId: 0, //某一个三级分类的ID
    categoryLevel: 3, //代表的是给三级分类新增平台属性
  });
  scene.value = 1;
};
//点击取消回到平台属性场景
const cancel = () => {
  scene.value = 0;
};
//点击添加属性值按钮回调
const addAttr = () => {
  //attrValueList属性值数组需要里面多一个对象(属性值{valueName})
  attrParams.attrValueList.push({
    valueName: "",
    flag: true,
  });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

//input失焦切换为span
const toLook = (row: any, index: number) => {
  if (row.valueName.trim() == "") {
    ElMessage.warning("属性值不能为空");
    //标识后面语句不在执行，不在显示span
    return;
  }
  let repeat = attrParams.attrValueList.find((item) => {
    if (row != item) {
      return row.valueName === item.valueName;
    }
  });
  if (repeat) {
    ElMessage.warning("属性值有重复的");
    attrParams.attrValueList.splice(index, 1);
    return;
  }
  row.flag = false;
};
//点击span切换为input
const toEdit = (row: any, index: number) => {
  row.flag = true;
  nextTick(() => {
    inputArr.value[index].focus();
  });
};
//点击删除删除平台属性值
const removeAttrValue = (index: number) => {
  attrParams.attrValueList.splice(index, 1);
};
//点击保存新增平台属性
const save = async () => {
  attrParams.categoryId = categoryStore.c3Id;
  try {
    ElMessage.success(attrParams.id ? "修改属性成功" : "新增属性成功");
    await reqAddOrUpdateAttr(attrParams);
    scene.value = 0;
    getAttrList();
  } catch (e) {
    ElMessage.error(attrParams.id ? "修改属性失败" : "新增属性失败");
  }
};
//点击平台属性场景的修改按钮
const updateAttr = (row: any) => {
  scene.value = 1;
  Object.assign(attrParams, cloneDeep(row));
};
//删除某一个已有平台属性
const deleteAttr = async (id) => {
  try {
    ElMessage.success("删除属性数据成功");
    await reqRemoveAttr(id);
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "error",
      message: `删除失败`,
    });
  }
};
//路由切换后清除分类的数据
onUnmounted(() => {
  //当前路由组件销毁之前,仓库数据前部情况
  categoryStore.c1Id = "";
  categoryStore.c2Id = "";
  categoryStore.c3Id = "";
  categoryStore.c1Arr = [];
  categoryStore.c2Arr = [];
  categoryStore.c3Arr = [];
});
</script>

<style scoped>
</style>